package hedron.editor;

import static hedron.i18n.Internationalization._;
import hedron.Activator;
import hedron.Application;
import hedron.db.model.Contact;
import hedron.dialog.ColumnDialog;
import hedron.dialog.CommentDialog;
import hedron.dialog.CommentViewDialog;
import hedron.dialog.ContactsDialog;
import hedron.editorinput.DummyEditorInput;
import hedron.ui.UIFactory;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.EditorPart;

public class ContactsEditor extends EditorPart {
	public static final String ID = "HEDRON.ContactsEditor";

	private FormToolkit toolkit;
	private ScrolledForm form;

	Text filterField;
	Table tableContacts;
	FormText detailsText;
	List<Contact> contacts;
	int limitResult = 200;
	Listener sortListener;
	int currentSorting = 0, previousSorting = 0;

	String[] sortColumns = { "C_NAME", "C_BULSTAT", "C_MOL", "C_TEL", "TYPE_NAME", "C_TAX", "C_DDS", "C_EMAIL",
			"C_CONTRY", "C_CITY", "C_ADDRESS", "C_BANK", "C_BANKACC" };

	String[] columnNames = { _("Column.CompanyName"), _("Column.BULSTAT"),
			_("Column.MOL"), _("Column.Phone"),_("Column.Type"),_("Column.VAT"),_("Column.DDS"),
			_("Column.e-mail"),_("Column.Country") ,
			_("Column.City"), _("Column.Address"), _("Column.Bank"), _("Column.BankAccount") };

	private static final String YES = _("Column.DDS.Yes");
	private static final String NO = _("Column.DDS.No");

	protected void initTableItem(TableItem item, Contact contact) {
		int i = 0;
		item.setData(contact);
		item.setText(i++, contact.C_NAME);
		item.setText(i++, contact.C_BULSTAT);
		item.setText(i++, contact.C_MOL);
		item.setText(i++, EditorUtils.flatString(contact.C_TEL));
		item.setText(i++, contact.TYPE_NAME);
		item.setText(i++, contact.C_TAX);
		item.setText(i++, contact.C_DDS ? YES : NO);

		item.setText(i++, EditorUtils.flatString(contact.C_EMAIL));
		item.setText(i++, contact.C_CONTRY);
		item.setText(i++, contact.C_CITY);
		item.setText(i++, EditorUtils.flatString(contact.C_ADDRESS));
		item.setText(i++, contact.C_BANK);
		item.setText(i++, contact.C_BANKACC);
		item.setText(i++, contact.C_FAX);
	}

	void refresh() {
		if (contacts != null) contacts.clear();
		contacts = Application.CONTACTS.getContacts(filterField.getText(), limitResult, sortColumns[currentSorting],
				previousSorting == currentSorting ? "ASC" : "DESC");

		if (tableContacts != null) {
			tableContacts.setRedraw(false);
			tableContacts.removeAll();

			for (Contact contact : contacts) {
				TableItem item = new TableItem(tableContacts, SWT.NONE);
				initTableItem(item, contact);
			}

			for (int i = 0; i < columnNames.length; i++) {
				tableContacts.getColumn(i).pack();
			}
			if (contacts.size() > 0) {
				tableContacts.setSelection(0);
				actionSelectContact(contacts.get(0));
			} else {
				detailsText.setText("<form></form>", true, false);
			}
			tableContacts.setRedraw(true);
		}
	}

	@Override
	public void init(IEditorSite site, IEditorInput input) throws PartInitException {
		setSite(site);
		setInput(input);
		setTitleImage(Activator.getImage("icons/contacts.png"));

		sortListener = new Listener() {
			public void handleEvent(Event e) {
				if (e.widget instanceof TableColumn) {
					int sortColumn = 0;
					for (; sortColumn < columnNames.length; sortColumn++) {
						if (columnNames[sortColumn].equals(((TableColumn) e.widget).getText())) {
							break;
						}
					}
					currentSorting = sortColumn;
					tableContacts.setSortColumn((TableColumn) e.widget);
					if (previousSorting != currentSorting) {
						tableContacts.setSortDirection(SWT.UP);
						previousSorting = currentSorting;
					} else {
						tableContacts.setSortDirection(SWT.DOWN);
						previousSorting = -1;
					}
					refresh();
				}
			}
		};
	}

	public void dispose() {
		toolkit.dispose();
		super.dispose();
	}

	@Override
	public void setFocus() {
		filterField.setFocus();
	}

	void actionAddContact() {
		Contact contact = new Contact();
		actionEditContact(contact);
	}

	void actionEditContact(Contact contact) {
		ContactsDialog dialog = new ContactsDialog(Application.getActiveWorkbench().getShell(), contact);
		dialog.open();
		refresh();
	}

	void actionSelectContact(Contact contact) {
		final String separator = ": ";
		final String br = "<br/>";
		final String pp = "</p><p>";
		StringBuilder details = new StringBuilder();
		details.append("<form><p><b>");
		details.append(EditorUtils.formString(contact.C_NAME)).append("</b> - ").append(
				EditorUtils.formString(contact.TYPE_NAME));
		details.append(pp).append(EditorUtils.formString(contact.C_MOL));
		details.append(pp).append(EditorUtils.formString(contact.C_EMAIL));
		details.append(br).append(EditorUtils.formString(contact.C_TEL));
		if (contact.C_FAX.length() > 0) {
			details.append(br).append(_("Editor.Contacts.Info.CompanyInfo")).append(separator);
			details.append(EditorUtils.formString(contact.C_TEL));
		}
		details.append("<br/><br/></p><p><b>").append(_("Column.Address")).append("</b>");
		details.append(br).append(EditorUtils.formString(contact.C_ADDRESS));
		details.append(br).append(EditorUtils.formString(contact.C_CITY));
		details.append(br).append(EditorUtils.formString(contact.C_CONTRY));
		details.append("<br/><br/></p><p><b>").append(_("Editor.Contacts.Info.CompanyInfo")).append("</b>");
		if (contact.C_DDS) {
			details.append(br).append(_("Editor.Contacts.Info.DDS"));
		}
		details.append(br).append(_("Column.BULSTAT")).append(separator).append(
				EditorUtils.formString(contact.C_BULSTAT));
		details.append(br).append(_("Column.VAT")).append(separator).append(EditorUtils.formString(contact.C_TAX));
		details.append(pp).append(_("Column.BankAccount")).append(separator).append(
				EditorUtils.formString(contact.C_BANKACC));
		details.append(br).append(_("Column.Bank")).append(separator).append(EditorUtils.formString(contact.C_BANK));
		details.append(pp).append(EditorUtils.formString(contact.C_NOTE1));
		details.append(br).append(EditorUtils.formString(contact.C_NOTE2));
		details.append("</p></form>");
		detailsText.setText(details.toString(), true, false);
	}
	
	private static final String layout = "<layout align=\"FILL\" valign=\"FILL\">"
			+ "<section text=\"Editor.Contacts.Section.Search\" columns=\"3\" align=\"FILL\" valign=\"BEGINING\">"
			+ "     <label text=\"Editor.Contacts.Label.Search\" align=\"BEGINING\" valign=\"CENTER\"/>"
			+ "     <text  id=\"filterField\" align=\"FILL\" valign=\"CENTER\"/>"
			+ "     <button id=\"searchButton\" text=\"Editor.Contacts.Button.Search\" icon=\"icons/search.png\" width=\"80\" height=\"20\" align=\"BEGINING\" valign=\"CENTER\"/>"
			+ "</section>"
			+ "<splitter horizontal=\"72\"  align=\"FILL\" valign=\"FILL\">"
			+ "  <section text=\"Editor.Contacts.Section.Contacts\" align=\"FILL\" valign=\"FILL\">"
			+ "     <table id=\"tableContacts\" fullselection=\"true\" align=\"FILL\" valign=\"FILL\"/>"
			+ "     <button id=\"limitButton\" text=\"Editor.Contacts.Label.Limit\" check=\"true\" align=\"BEGINING\" valign=\"BEGINNING\"/>"
			+ "  </section>"
			+ "  <section text=\"Editor.Contacts.Section.Info\" columns=\"2\" align=\"FILL\" valign=\"FILL\">"
			+ "     <text  id=\"detailsText\" html=\"true\" colspan=\"2\" align=\"FILL\" valign=\"FILL\"/>"
			+ "     <button id=\"editButton\" text=\"Editor.Contacts.Button.Edit\" height=\"20\" align=\"FILL\" valign=\"BEGINNING\"/>"
			+ "     <button id=\"commentButton\" text=\"Editor.Contacts.Button.Comment\" height=\"20\" align=\"FILL\" valign=\"BEGINNING\"/>"
			+ "     <button id=\"viewButton\" text=\"Editor.Contacts.Button.ViewComments\" colspan=\"2\" height=\"20\" align=\"FILL\" valign=\"BEGINNING\"/>"
			+ "  </section>"
			+ "</splitter>"
			+ "</layout>";
	
	@Override
	public void createPartControl(Composite parent) {
		toolkit = new FormToolkit(parent.getDisplay());
		form = toolkit.createScrolledForm(parent);

		form.setText(_("Editor.Contacts.Title"));
		form.setBackgroundImage(Activator.getImage("icons/form_background.png"));

		// createPartControl1(form.getBody());

		Map<String, Control> components = UIFactory.createUI(form.getBody(), layout, toolkit);
		filterField = (Text) components.get("filterField");
		final Button searchButton = (Button) components.get("searchButton");
		tableContacts = (Table) components.get("tableContacts");
		final Button limitButton = (Button) components.get("limitButton");

		detailsText = (FormText) components.get("detailsText");
		final Button editButton = (Button) components.get("editButton");
		final Button commentButton = (Button) components.get("commentButton");
		final Button viewButton = (Button) components.get("viewButton");

		filterField.addKeyListener(new KeyListener() {
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.keyCode == 13) {
					refresh();
				}
			}
			@Override
			public void keyPressed(KeyEvent e) {}
		});

		searchButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				refresh();
			}
		});

		{
			for (int i = 0; i < columnNames.length; i++) {
				TableColumn column = new TableColumn(tableContacts, SWT.NONE);
				column.setText(columnNames[i]);
				column.addListener(SWT.Selection, sortListener);
			}
			tableContacts.setHeaderVisible(true);
			tableContacts.setLinesVisible(true);

			tableContacts.setSortColumn(tableContacts.getColumn(0));
			tableContacts.setSortDirection(SWT.UP);

			tableContacts.addListener(SWT.MouseDoubleClick, new Listener() {
				@Override
				public void handleEvent(Event event) {
					int selection = tableContacts.getSelectionIndex();
					if (selection >= 0) {
						Contact contact = (Contact) tableContacts.getItem(selection).getData();
						actionEditContact(contact);
					}
				}
			});

			tableContacts.addSelectionListener(new SelectionListener() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					TableItem[] items = tableContacts.getSelection();
					if (items != null && items.length > 0) {
						Contact contact = (Contact) items[0].getData();
						actionSelectContact(contact);
					}
				}

				@Override
				public void widgetDefaultSelected(SelectionEvent e) {}
			});
		}

		{// limit button
			limitButton.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent e) {
					limitResult = ((Button) e.widget).getSelection() ? 200 : 0;
					refresh();
				}
			});
			limitButton.setSelection(true);
			limitResult = 200;
		}

		editButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				TableItem[] items = tableContacts.getSelection();
				if (items != null && items.length > 0) {
					Contact contact = (Contact) items[0].getData();
					actionEditContact(contact);
				}
			}
		});

		commentButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				int selection = tableContacts.getSelectionIndex();
				if (selection >= 0) {
					Contact contact = (Contact) tableContacts.getItem(selection).getData();
					CommentDialog dialog = new CommentDialog(Application.getActiveWorkbench().getShell(),
							contact.C_NAME);
					dialog.open();
				}
			}
		});

		viewButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				int selection = tableContacts.getSelectionIndex();
				if (selection >= 0) {
					Contact contact = (Contact) tableContacts.getItem(selection).getData();
					CommentViewDialog dialog = new CommentViewDialog(Application.getActiveWorkbench().getShell(),
							contact);
					dialog.open();
				}
			}
		});

		// tool-bar buttons
		{
			Action action = new Action("add", Action.AS_PUSH_BUTTON) { //$NON-NLS-1$
				public void run() {
					actionAddContact();
				}
			};
			action.setToolTipText(_("Editor.Contacts.Tooltip.Add"));
			action.setImageDescriptor(Activator.getImageDescriptor("icons/add.png"));
			form.getToolBarManager().add(action);
		}
		{
			Action action = new Action("edit", Action.AS_PUSH_BUTTON) { //$NON-NLS-1$
				public void run() {
					TableItem[] items = tableContacts.getSelection();
					if (items != null && items.length > 0) {
						Contact contact = (Contact) items[0].getData();
						actionEditContact(contact);
					}
				}
			};
			action.setToolTipText(_("Editor.Contacts.Tooltip.Edit"));
			action.setImageDescriptor(Activator.getImageDescriptor("icons/edit.png"));
			form.getToolBarManager().add(action);
		}
		{
			Action action = new Action("print", Action.AS_PUSH_BUTTON) { //$NON-NLS-1$
				public void run() {
					IWorkbenchPage page = getSite().getPage();
					try {
						ColumnDialog dialog = new ColumnDialog(Application.getActiveWorkbench().getShell(),
								tableContacts);

						if (dialog.open() == Window.OK) {
							final boolean[] selectedColums = dialog.selectedColums;
							final TableColumn[] columns = tableContacts.getColumns();
							final StringBuilder html = new StringBuilder();

							html.append("<HTML><head><STYLE type=\"text/css\"> "
									+ "body{ background-color: #FFFF; color: #606060; font-size: 13px; font-family: tahoma, verdana, arial, sans-serif; margin: 0; padding: 0; height: 100%; } "
									+ "table { background-color: #FFFFFF; font-size: 11px; }"
									+ "</STYLE></head><BODY><table border=1 width='100%' cellspacing=0 cellpadding=1 style='border: #ccc solid 1px;'>");
							html.append("<tr>");
							for (int i = 0; i < selectedColums.length; i++) {
								if (selectedColums[i]) {
									html.append("<td nowrap=true><b>");
									html.append(columns[i].getText());
									html.append("</b></td>");
								}
							}
							html.append("</tr>");
							for (int j = 0; j < tableContacts.getItemCount(); j++) {

								html.append("<tr>");
								for (int i = 0; i < selectedColums.length; i++) {
									if (selectedColums[i]) {
										html.append("<td>");
										html.append(tableContacts.getItem(j).getText(i));
										html.append("&nbsp;</td>");
									}
								}
								html.append("</tr>");
							}
							html.append("</table></BODY></HTML>");

							String name = _("Dialog.Contacts.Print");
							DummyEditorInput editorInput = new DummyEditorInput(Application.ID.getUID(), name);
							editorInput.setData(html);
							page.openEditor(editorInput, HTMLPrintEditor.ID);
						}
					} catch (PartInitException e) {
						Application.log.log(Level.OFF, "", e);
					}
				}
			};
			action.setToolTipText(_("Editor.Contacts.Tooltip.Print"));
			action.setImageDescriptor(Activator.getImageDescriptor("icons/print.png"));
			form.getToolBarManager().add(action);
		}
		{
			Action action = new Action("refresh", Action.AS_PUSH_BUTTON) { //$NON-NLS-1$
				public void run() {
					refresh();
				}
			};
			action.setToolTipText(_("Editor.Contacts.Tooltip.Refresh"));
			action.setImageDescriptor(Activator.getImageDescriptor("icons/refresh.png"));
			form.getToolBarManager().add(action);
		}
		form.updateToolBar();
		refresh();
	}

	@Override
	public boolean isDirty() {
		return false;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	@Override
	public void doSave(IProgressMonitor monitor) {}

	@Override
	public void doSaveAs() {}

}